package com.imay.live.activity.family.controller;

import android.content.res.Resources;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.imay.base.activity.BaseActivity;
import com.imay.live.R;
import com.imay.live.activity.RoomLiveNormalActivity;
import com.imay.live.activity.RoomPushNormalActivity;
import com.imay.live.activity.RoomPushShortActivity;
import com.imay.live.activity.family.FamilyParams;
import com.imay.live.activity.family.util.DesignViewUtils;
import com.imay.live.fragment.dynamics.DynamicsParams;
import com.imay.live.helper.UrlHelper;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.model.FamilyModel;
import com.imay.live.model.FamilyUserModel;
import com.imay.live.model.FeedModel;
import com.imay.live.model.MenuItemModel;
import com.imay.live.model.RankingModel;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.ShortLiveInfoModel;
import com.imay.live.utils.AnimationUtil;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ViewUtil;
import com.imay.live.view.FamilyItemView;
import com.imay.live.view.FamilyItemViewRound;
import com.imay.live.view.dialog.ChoiseDialogFragment;
import com.imay.live.view.refresh.RefreshView;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/31 0031.
 */

public class FamilyHomeController extends BaseFamilyController implements AppBarLayout.OnOffsetChangedListener {

    private List<MenuItemModel> menu;

    private int menustatus = -1;

    public static final int MENU_ACTION_FAMILY_MODIFY = 201;
    public static final int MENU_ACTION_FAMILY_JOIN = 202;
    public static final int MENU_ACTION_FAMILY_OUT = 203;

    private FamilyItemView fiv_family_lives, fiv_family_person, fiv_family_con;
    private FamilyItemViewRound fiv_family_dynamics, fiv_family_super;
    private View ll_family_im, tv_family_apply;
    private AppBarLayout app_bar_layout;
    private View rl_family_home_title;
    private ImageView iv_family_img;
    private TextView tv_family_im_count, tv_family_title;
    private NestedScrollView nsv_family;

    private int viewHight;
    private float titleHight;
    private float mLastScale;
    private float mLastAlpha;
    private float mLastAlpha2;
    private TextView tv_family_home_title, tv_family_home_descript, tv_family_home_icon;

    private boolean isAppBarLayoutOpen;

    @Override
    protected void initView() {
        Toolbar toolbar = ViewUtil.findView(activity, R.id.toolbar);
        toolbar.setTitle("");
        toolbar.setSubtitle("");
        ((AppCompatActivity) activity).setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.onBackPressed();
            }
        });
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) toolbar.getLayoutParams();
        params.setMargins(0, ((BaseActivity) activity).getStatusBarHeight(), 0, 0);

        app_bar_layout = ViewUtil.findView(activity, R.id.app_bar_layout);
        rl_family_home_title = ViewUtil.findView(activity, R.id.rl_family_home_title);
        tv_family_home_title = ViewUtil.findView(activity, R.id.tv_family_home_title);
        tv_family_home_icon = ViewUtil.findView(activity, R.id.tv_family_home_icon);
        iv_family_img = ViewUtil.findView(activity, R.id.iv_family_img);
        tv_family_home_descript = ViewUtil.findView(activity, R.id.tv_family_home_descript);
        ll_family_im = ViewUtil.findView(activity, R.id.ll_family_im);
        fiv_family_lives = ViewUtil.findView(activity, R.id.fiv_family_lives);
        fiv_family_dynamics = ViewUtil.findView(activity, R.id.fiv_family_dynamics);
        fiv_family_super = ViewUtil.findView(activity, R.id.fiv_family_super);
        fiv_family_person = ViewUtil.findView(activity, R.id.fiv_family_person);
        fiv_family_con = ViewUtil.findView(activity, R.id.fiv_family_con);
        tv_family_apply = ViewUtil.findView(activity, R.id.tv_family_apply);
        tv_family_im_count = ViewUtil.findView(activity, R.id.tv_family_im_count);
        nsv_family = ViewUtil.findView(activity, R.id.nsv_family);
        tv_family_title = ViewUtil.findView(activity, R.id.tv_family_title);

        fiv_family_lives.setTitle(R.string.str_family_live);
        fiv_family_dynamics.setTitle(R.string.str_family_dynamics);
        fiv_family_super.setTitle(R.string.str_family_super);
        fiv_family_person.setName(R.string.str_family_person);
        fiv_family_con.setName(R.string.str_family_con);

        initListener();
        refreshUnreadView();
    }

    public void refreshUnreadView() {
        tv_family_im_count.setVisibility(View.VISIBLE);
        if (!FamilyAccountManager.isMyFamilyLocked()) {
            int count = NIMClient.getService(MsgService.class).getTotalUnreadCount();
            if (count > 999) {
                tv_family_im_count.setText(activity.getString(R.string.str_family_im_count_w));
            } else if (count == 0) {
                tv_family_im_count.setVisibility(View.INVISIBLE);
            } else {
                tv_family_im_count.setText(activity.getString(R.string.str_family_im_count, count));
            }
        } else {
            tv_family_im_count.setVisibility(View.INVISIBLE);
        }
    }

    private void initListener() {
        if (activity instanceof View.OnClickListener) {
            rl_family_home_title.setOnClickListener((View.OnClickListener) activity);
            ll_family_im.setOnClickListener((View.OnClickListener) activity);
            fiv_family_lives.setOnClickListener((View.OnClickListener) activity);
            fiv_family_dynamics.setOnClickListener((View.OnClickListener) activity);
            fiv_family_super.setOnClickListener((View.OnClickListener) activity);
            fiv_family_person.setOnClickListener((View.OnClickListener) activity);
            fiv_family_con.setOnClickListener((View.OnClickListener) activity);
            tv_family_apply.setOnClickListener((View.OnClickListener) activity);
        }
    }

    public void setOtherViewHide() {
        ll_family_im.setVisibility(View.GONE);
        fiv_family_con.setVisibility(View.GONE);
        fiv_family_person.setName("");
        tv_family_apply.setVisibility(View.VISIBLE);
        fiv_family_lives.setImageHidden();
        fiv_family_dynamics.setCountHidden();
        fiv_family_super.setCountHidden();
    }

    /**
     * @param menus
     */
    public void initMenu(int menus, ChoiseDialogFragment.OnItemClickListener itemClickListener) {
        if (menus != menustatus) {
            menustatus = menus;
            switch (menustatus) {
                case FamilyParams.ADMIN_BIG:
                    menu = new ArrayList<MenuItemModel>() {{
                        add(new MenuItemModel(MENU_ACTION_FAMILY_MODIFY, R.string.str_family_menu_modify));
                        add(new MenuItemModel(MENU_ACTION_FAMILY_JOIN, R.string.str_family_menu_join));
                        add(new MenuItemModel(MENU_ACTION_FAMILY_OUT, R.string.str_family_menu_out));
                    }};
                    break;
                case FamilyParams.ADMIN_MID:
                    menu = new ArrayList<MenuItemModel>() {{
                        add(new MenuItemModel(MENU_ACTION_FAMILY_JOIN, R.string.str_family_menu_join));
                        add(new MenuItemModel(MENU_ACTION_FAMILY_OUT, R.string.str_family_menu_out));
                    }};
                    break;
                case FamilyParams.ADMIN_SMALL:
                    menu = new ArrayList<MenuItemModel>() {{
                        add(new MenuItemModel(MENU_ACTION_FAMILY_OUT, R.string.str_family_menu_out));
                    }};
                    break;
            }
        }
        if (menu != null && !menu.isEmpty()) {
            ChoiseDialogFragment.show(((AppCompatActivity) activity).getSupportFragmentManager(), menu, this.hashCode(), itemClickListener);
        }
    }

    public void onPause() {
        app_bar_layout.removeOnOffsetChangedListener(this);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        isAppBarLayoutOpen = DesignViewUtils.isAppBarLayoutOpen(verticalOffset);
        dispatchScroll();
        if (verticalOffset > 0) {
            return;
        }
        scaleTitleBar(verticalOffset);
    }

    private void dispatchScroll() {
        if (refresh_view == null) {
            return;
        }
        if (isAppBarLayoutOpen) {
            refresh_view.setEnableRefresh(true);
        } else {
            refresh_view.setEnableRefresh(false);
        }
    }

    /**
     * 缩放titlebar
     *
     * @param verticalOffset
     */
    protected void scaleTitleBar(int verticalOffset) {
        float offsetPercent = verticalOffset * 1F / viewHight * 1F;
        float toScale = 1 + (offsetPercent * 3 / 7F);
        float toAlpha = 1 + (offsetPercent * 10 / 7F);
        float offsetPercent2 = verticalOffset * 1F / titleHight * 1F;
        float toAlpha2 = -6 - (offsetPercent2 * 10 / 7F);
        AlphaAnimation alphaAnimation = null;
        AlphaAnimation alphaAnimation2 = null;
        if (mLastScale != toScale) {
            mLastScale = toScale;
        }
        if (mLastAlpha != toAlpha && toAlpha <= 1) {
            alphaAnimation = new AlphaAnimation(mLastAlpha, toAlpha);
            mLastAlpha = toAlpha;
        }
        if (alphaAnimation != null) {
            AnimationUtil.startAnimation(rl_family_home_title, alphaAnimation);
        }

        if (mLastAlpha2 != toAlpha2 && toAlpha2 <= 1) {
            alphaAnimation2 = new AlphaAnimation(mLastAlpha2, toAlpha2);
            mLastAlpha2 = toAlpha2;
        } else if (toAlpha2 > 1 && mLastAlpha2 < 1) {
            alphaAnimation2 = new AlphaAnimation(mLastAlpha2, 1);
            mLastAlpha2 = 1;
        }
        if (alphaAnimation2 != null) {
            AnimationUtil.startAnimation(tv_family_title, alphaAnimation2);
        }
    }

    public void setViewHight(int statusBarHeight) {
        Resources r = activity.getResources();
        this.viewHight = (int) (r.getDimension(R.dimen.family_home_applayout_bar) - r.getDimension(R.dimen.title_bar_height)) - statusBarHeight;
        this.titleHight = r.getDimension(R.dimen.title_bar_height);
    }

    public void setTitleData(FamilyModel titleData) {
        if (titleData == null) {
            return;
        }
        tv_family_home_title.setText(titleData.getName());
        tv_family_home_icon.setText(Integer.toString(titleData.getLv()));
        tv_family_home_descript.setText(titleData.getAnnouncement());
        tv_family_title.setText(titleData.getName());
//        int size = (int) activity.getResources().getDimension(R.dimen.family_home_applayout_bar);
        GlideUtil.loadImage(iv_family_img, titleData.getUrl());
    }

    public void setLiveData(final List<RoomInfoModel> liveData) {
        if (liveData == null) {
            return;
        }
        if (liveData.isEmpty()) {
            fiv_family_lives.setOnClickListener(null);
        } else {
            if (activity instanceof View.OnClickListener) {
                fiv_family_lives.setOnClickListener((View.OnClickListener) activity);
            }
        }
        List<String> images = new ArrayList<>();
        for (RoomInfoModel roomInfo : liveData) {
            images.add(roomInfo.getImgFace());
        }
        Log.e("vanka_log", "live datas get");
        fiv_family_lives.setNewData(images, true);
        fiv_family_lives.setViewHidden();
    }

    /**
     * 他人切面可以直接跳主播
     *
     * @param liveData
     */
    public void setLiveItemClick(final List<RoomInfoModel> liveData) {
        fiv_family_lives.setOnItemClick(new FamilyItemView.OnItemClick() {
            @Override
            public void itemClick(int position) {
                RoomLiveNormalActivity.startActivity(activity, (ArrayList<RoomInfoModel>) liveData, position);
            }
        });
    }

    public void setShortLiveData(ArrayList<ShortLiveInfoModel> shortLiveData) {
        if (shortLiveData == null) {
            return;
        }
        if (shortLiveData.isEmpty()) {
            fiv_family_super.setOnClickListener(null);
        } else {
            if (activity instanceof View.OnClickListener) {
                fiv_family_super.setOnClickListener((View.OnClickListener) activity);
            }
        }
        List<String> images = new ArrayList<>();
        for (ShortLiveInfoModel item : shortLiveData) {
            images.add(UrlHelper.getVideoThumbUrl(item.getVideoUrl()));
        }
        fiv_family_super.setNewData(images, false);
    }

    public void setFeedData(ArrayList<FeedModel> feedData) {
        if (feedData == null) {
            return;
        }
        if (feedData.isEmpty()) {
            fiv_family_dynamics.setOnClickListener(null);
        } else {
            if (activity instanceof View.OnClickListener) {
                fiv_family_dynamics.setOnClickListener((View.OnClickListener) activity);
            }
        }
        List<String> images = new ArrayList<>();
        for (FeedModel item : feedData) {
            if (item.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_IMAGE) {
                images.add(item.getImgUrl());
            } else if (item.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_VIDEO) {
                images.add(UrlHelper.getVideoThumbUrl(item.getVideoUrl()));
            }
        }
        fiv_family_dynamics.setNewData(images, true);
    }

    public void setUserData(FamilyUserModel userData) {
        if (userData == null) {
            return;
        }
        List<String> images = new ArrayList<>();
        List<Integer> familyAdmin = new ArrayList<>();
        for (FamilyUserModel.FamilyUsersBean user : userData.getFamilyUsers()) {
            images.add(user.getImgHead());
            familyAdmin.add(user.getAdmin());
        }
        fiv_family_person.setNewData(images, false);
        fiv_family_person.setAdmin(familyAdmin);
    }

    public void setLiveCount(int liveCount) {
        fiv_family_lives.setLiveCount(liveCount);
    }

    public void setRankData(ArrayList<RankingModel> rankDatas) {
        if (rankDatas == null) {
            return;
        }
        if (rankDatas.isEmpty()) {
            fiv_family_con.setOnClickListener(null);
        } else {
            if (activity instanceof View.OnClickListener) {
                fiv_family_con.setOnClickListener((View.OnClickListener) activity);
            }
        }
        List<String> images = new ArrayList<>();
        List<Integer> ranks = new ArrayList<>();
        for (RankingModel user : rankDatas) {
            images.add(user.getUser().getImgHead());
            ranks.add(user.getRank());
        }
        fiv_family_con.setNewData(images, false);
        fiv_family_con.setRank(ranks);
    }

    public void setRresh(RefreshListenerAdapter reshListener) {
        refresh_view = ViewUtil.findView(activity, R.id.refresh_view);
        refresh_view.setHeaderView(new RefreshView(activity));
        refresh_view.setEnableLoadmore(false);
        refresh_view.setEnableOverScroll(false);
        app_bar_layout.addOnOffsetChangedListener(this);
        if (refresh_view != null) {
            refresh_view.setOnRefreshListener(reshListener);
        }
    }

    public void setFeedCount(int feedCount) {
        if (feedCount < 99) {
            fiv_family_dynamics.setCount(String.valueOf(feedCount));
        } else {
            fiv_family_dynamics.setCount("99+");
        }
    }

    public void setShortLiveCount(int shortLiveCount) {
        if (shortLiveCount < 99) {
            fiv_family_super.setCount(String.valueOf(shortLiveCount));
        } else {
            fiv_family_super.setCount("99+");
        }
    }

    /**
     * 设置我的家族view
     */
    public void setMeView() {
        if (fiv_family_lives != null) {
            fiv_family_lives.setOnNodataClick(new FamilyItemView.OnNodataClick() {
                @Override
                public void noDataClick() {
                    RoomPushNormalActivity.startActivity(activity);
                }
            });
        }
        if (fiv_family_super != null) {
            fiv_family_super.setOnNodataClick(new FamilyItemViewRound.OnNodataClick() {
                @Override
                public void noDataClick() {
                    RoomPushShortActivity.startActivity(activity);
                }
            });
        }
    }

    /**
     * 家族封禁之后显示情况
     */
    public void setLockedRefreshView() {
        fiv_family_con.hiddenImageView();
        fiv_family_person.hiddenImageView();
    }
}
